<template>
  <div class="account" style="height: 100%">
    <je-grid
      ref="xTable"
      align="center"
      stripe
      type
      keep-source
      :row-config="{ keyField: 'id' }"
      :data="tableData"
      :auto-load="true"
      size="mini"
      :loading="loading"
      show-overflow="ellipsis"
      height="100%"
      resizable
      auto-resize
      header-row-class-name="headerHeight"
      :filter-config="{ showIcon: false }"
    >
      <template #pager>
        <je-pager
          v-model:current-page="tablePage.currentPage"
          v-model:page-size="tablePage.pageSize"
          :page-sizes="tablePage.pageSizes"
          align="left"
          style="height: 40px; padding: 0 10px"
          background
          :size="size"
          :total="tablePage.totalResult"
          :layouts="['Sizes', 'Message', 'JumpNumber', 'FullJump', 'Refresh']"
          @load="loadAccountEvent"
        />
      </template>

      <je-column type="checkbox" width="40" field="checked" />
      <je-column type="seq" width="50" title="No."></je-column>
      <je-column
        v-if="remark === 'Organization'"
        field="ACCOUNT_NAME"
        title="姓名"
        width="240"
        type="html"
      ></je-column>
      <je-column
        v-if="remark === 'Departmente' || remark === 'Role' || remark === 'Developer'"
        field="ACCOUNT_NAME"
        title="姓名"
        width="100"
        type="html"
      ></je-column>
      <je-column field="ACCOUNT_CODE" title="账号" width="150" type="html"></je-column>
      <je-column
        field="SY_ORG_NAME"
        title="机构"
        width="150"
        :filters="allORGs"
        :filter-method="filterNameMethod"
        type="html"
      ></je-column>
      <je-column
        v-if="remark === 'Departmente' || remark === 'Organization'"
        field="ACCOUNTDEPT_DEPT_NAME"
        title="部门"
        width="230"
        type="html"
      >
        <template #default="{ row }">
          {{ row.ACCOUNTROLE_DEPT_NAME || row.ACCOUNTDEPT_DEPT_NAME
          }}<i
            v-if="row.ACCOUNTROLE_MAIN_CODE == '0'"
            class="fas fa-code-branch"
            style="color: rgb(50, 101, 245); margin-left: 6px; font-size: 12px"
          ></i
        ></template>
      </je-column>
      <je-column
        v-if="remark === 'Role'"
        field="ACCOUNTROLE_DEPT_NAME"
        title="部门"
        width="230"
        type="html"
      >
        <template #default="{ row }">
          {{ row.ACCOUNTROLE_DEPT_NAME
          }}<i
            v-if="row.ACCOUNTROLE_MAIN_CODE == '0'"
            class="fas fa-code-branch"
            style="color: rgb(50, 101, 245); margin-left: 6px; font-size: 12px"
          ></i>
        </template>
      </je-column>
      <je-column field="ACCOUNT_MAIL" title="邮箱" width="230"></je-column>
      <je-column
        field="ACCOUNTROLE_SY_CREATEUSERNAME"
        title="创建人"
        width="100"
        type="html"
      ></je-column>
      <je-column
        v-if="remark === 'Departmente' || remark === 'Organization' || remark === 'PermissionGroup'"
        field="SY_CREATETIME"
        title="创建时间"
        width="200"
      ></je-column>
      <je-column
        v-if="remark === 'Role' || remark === 'Developer'"
        field="ACCOUNTROLE_SY_CREATETIME"
        title="创建时间"
        width="200"
      ></je-column>
      <je-column field="ACCOUNTDEPT_DEPT_ID" title="操作" width="200">
        <template #default="{ row }">
          <je-button
            v-if="remark === 'Role' || remark === 'Developer'"
            type="link"
            @click="remove(row)"
            ><span style="color: #d8001b">{{ $t('account.remove') }}</span></je-button
          >
          <je-button type="link" @click="gobalBuyer(row)"
            ><span style="color: #52b8f1">{{ $t('account.look') }}</span></je-button
          >
        </template>
      </je-column>

      <template #tbar>
        <div class="content">
          <je-toolbar space="0" class="content-toolbar">
            <div v-if="remark === 'Role'" class="btns">
              <je-button type="text" :disabled="btnFlag" @click="add"
                ><i class="fal fa-user-plus"></i><span>添加人员账号</span></je-button
              >
              <je-button type="text" :disabled="btnFlag" @click="showImport = true"
                ><i class="fal fa-file-import"></i><span>按部门导入</span></je-button
              >
              <je-dropdown :trigger="['click']">
                <je-button type="text" :disabled="btnFlag" @click="importORGBtn"
                  ><i class="fal fa-landmark"></i> 通过机构添加账号 <i class="fal fa-angle-down"></i
                ></je-button>
                <template #overlay>
                  <je-menu mode="vertical">
                    <template v-if="orgList.length > 0">
                      <je-menu-item
                        v-for="item in orgList"
                        :key="item.bean.JE_RBAC_ORG_ID"
                        @click="selectByOrg(item)"
                        >{{ item.bean.ORG_NAME }}
                      </je-menu-item>
                    </template>
                    <je-menu-item v-else>暂无数据</je-menu-item>
                  </je-menu>
                </template>
              </je-dropdown>
              <je-button type="text" :disabled="btnFlag" @click="removeBySelect"
                ><i class="fal fa-user-times"></i><span>移除账号</span></je-button
              >
            </div>
            <div v-if="remark === 'Developer'" class="btns">
              <je-button type="text" :disabled="btnFlag" @click="addDeveloper"
                ><i class="fal fa-user-plus"></i><span>添加开发成员</span></je-button
              >
              <je-button type="text" :disabled="btnFlag" @click="removeBySelect"
                ><i class="fal fa-user-times"></i><span>移除账号</span></je-button
              >
            </div>
            <div v-if="remark === 'Departmente'" class="tip"
              ><i class="fal fa-exclamation-circle"></i>为部门员工设置功能权限。</div
            >
            <div v-if="remark === 'Organization'" class="tip"
              ><i class="fal fa-exclamation-circle"></i>为机构全体人员设置功能权限。</div
            >
            <div v-if="remark === 'PermissionGroup'" class="tip"
              ><i class="fal fa-exclamation-circle"></i>
              权限组是权限配置的集合，使用权限组的角色将具有权限组配置的权限。权限组无需维护账号配置。</div
            >
            <je-tb-fill />
            <je-select
              v-model:value="organText"
              :disabled="btnFlag"
              :style="{ width: '120px' }"
              :options="allORGs"
              :allow-clear="false"
              :bordered="false"
              :get-popup-container="getPopupContainer"
              @change="(value, option) => selectDepartment(value, option)"
              @click="clickSelectEvent"
            ></je-select>
            <div class="searchWrap">
              <je-input-search
                v-model:value.trim="searchValue"
                class="search"
                placeholder="搜索"
                allow-clear
                enter-button="搜索"
                style="width: 280px"
                @search="searchEvent"
              >
                <template #prefix> <i class="fal fa-search" /> </template>
              </je-input-search>
            </div>
          </je-toolbar>
        </div>
      </template>
    </je-grid>
    <div v-if="showImport">
      <ImportByDepartment
        v-model:visible="showImport"
        :role-ids="theCurrID"
        @loadAccountEvent="loadAccountEvent"
      />
    </div>
    <div v-if="isShow">
      <ViewPermission v-model:visible="isShow" :type="dataType" :account-id="accountId" />
    </div>
  </div>
</template>

<script>
  import {
    defineAsyncComponent,
    defineComponent,
    onMounted,
    onUnmounted,
    reactive,
    ref,
  } from 'vue';

  import { Grid, Toolbar, Input, Button, Menu, Modal, Pager, Select } from '@jecloud/ui';

  import { Dropdown } from 'ant-design-vue';

  import VueEvent from '@/helper/model/event';

  import { SelectWindow } from '@jecloud/func';

  import XEUtils from 'xe-utils';

  import {
    importAccountByOrgsApi,
    importAccountDeptByDepartmentAccounteApi,
    importByDepartmentUsersApi,
    loadAccountApi,
    loadOrgApi,
    removeAccountApi,
  } from '@/api';

  export default defineComponent({
    name: 'Account',
    components: {
      ImportByDepartment: defineAsyncComponent(() => import('./import-by-department.vue')),
      ViewPermission: defineAsyncComponent(() => import('./view-permission.vue')),
      JeGrid: Grid,
      JeColumn: Grid.Column,
      JeToolbar: Toolbar,
      JeButton: Button,
      JeTbFill: Toolbar.Fill,
      JeInputSearch: Input.Search,
      JeDropdown: Dropdown,
      JeMenu: Menu,
      JeMenuItem: Menu.Item,
      JePager: Pager,
      JeSelect: Select,
    },
    props: {
      roleId: {
        type: String,
        default: '',
      },
      type: {
        type: String,
        default: '',
      },
    },
    setup(props) {
      // 表单数据
      const tableData = ref([]);
      const loading = ref(false);
      // 获取表单数据
      let _currrntType = null;
      let theCurrID = ref(null);
      onMounted(() => {
        initData();
      });

      //初始化数据
      const initData = () => {
        if (props.type == 'develop') {
          _currrntType = 'role';
        } else {
          _currrntType = props.type;
        }
        theCurrID.value = props.roleId;
        if (theCurrID.value) {
          loadAccountEvent();
        }
        clickAllOrgEvent();
      };

      // 请求表单数据
      const loadAccountEvent = (search) => {
        // 按钮不再禁用状态且_currrntType不为permissionGroup才继续往下执行
        if (btnFlag.value) return false;
        if (_currrntType === 'permissionGroup') return false;
        loading.value = true;
        // search不为String类型，search为空
        if (typeof search !== 'string') {
          search = null;
        }
        // 开发者加入
        //拼接机构查询条件
        loadAccountApi({
          type: _currrntType,
          ids: theCurrID.value,
          page: tablePage.currentPage,
          start: (tablePage.currentPage - 1) * tablePage.pageSize,
          limit: tablePage.pageSize,
          orgId: search,
          loadTYpe: remark.value === 'Developer' && 'develop',
        }).then((res) => {
          tableData.value = res.rows;
          columnID.value = [];
          columnCode.value = [];
          // 处理过滤数据
          tableData.value.forEach((item) => {
            if (!columnID.value.includes(item.ACCOUNTROLE_DEPT_ID)) {
              if (item.ACCOUNTROLE_DEPT_ID) {
                columnID.value.push(item.ACCOUNTROLE_DEPT_ID);
              }
            }
            if (!columnCode.value.includes(item.ACCOUNT_CODE)) {
              columnCode.value.push(item.ACCOUNT_CODE);
            }
          });
          loading.value = false;
          tablePage.totalResult = tableData.value.length || 0;
        });
      };

      // 搜索
      const searchValue = ref(null);

      // 表格搜索
      const tablePage = reactive({
        currentPage: 1,
        pageSize: 30,
        pageSizes: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
        totalResult: 0,
      });

      // 搜索事件
      const searchEvent = () => {
        if (btnFlag.value) return false;
        // 搜索关键字
        const filterName = XEUtils.toValueString(searchValue.value).trim().toLowerCase();
        // 关键词不为空
        if (filterName) {
          let result = [];
          // 更新table
          loadAccountApi({
            type: _currrntType,
            ids: theCurrID.value,
            search: filterName,
          }).then((res) => {
            result = res.rows;
            loading.value = false;
            tablePage.totalResult = tableData.value.length || 0;
            const filterRE = new RegExp(filterName, 'gi'); // 匹配正则
            // 搜索项
            const searchProps = [
              'ACCOUNT_NAME',
              'ACCOUNT_CODE',
              'ACCOUNTDEPT_DEPT_NAME',
              'SY_CREATEUSERNAME',
            ];
            // 搜索结果
            const rest = result.filter((item) =>
              searchProps.some(
                (key) => XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterName) > -1,
              ),
            );
            // 搜索关键词高亮
            tableData.value = rest.map((row) => {
              const item = Object.assign({}, row);
              searchProps.forEach((key) => {
                item[key] = XEUtils.toValueString(item[key]).replace(
                  filterRE,
                  (match) => `<span class="keyword-lighten">${match}</span>`,
                );
              });
              return item;
            });
          });
        } else {
          loadAccountEvent();
        }
      };

      // 按部门导入的显隐
      const showImport = ref(false);
      // 当前选择的事角色，组织还是机构
      const remark = ref('Role');
      // 切换角色，组织还是机构
      const xTable = ref('xTable');

      // 切换角色组织机构的回调事件
      const leftComponentCB = (val) => {
        if (remark.value !== val) {
          tableData.value = [];
        }
        remark.value = val;
        searchValue.value = null;
        // 根据remark值判断是否显示checked列
        if (remark.value === 'Role' || remark.value === 'Developer') {
          xTable.value.showColumn(xTable.value.getColumnByField('checked'));
        } else {
          xTable.value.hideColumn(xTable.value.getColumnByField('checked'));
        }
      };

      // 查看权限
      // dialog的显示隐藏
      const isShow = ref(false);
      const accountId = ref(null);
      const dataType = ref(null);
      // 查看权限
      const gobalBuyer = (row) => {
        accountId.value = row.JE_RBAC_ACCOUNT_ID;
        dataType.value = _currrntType;
        isShow.value = true;
      };
      // 移除
      const remove = (row) => {
        Modal.confirm('您确定要移除该项吗？', () => {
          let strData = [
            { departmentId: row.ACCOUNTROLE_DEPT_ID, accountIds: row.JE_RBAC_ACCOUNT_ID },
          ];
          strData = JSON.stringify(strData);
          // 调用移除接口
          removeAccountApi({
            roleId: row.ACCOUNTROLE_ROLE_ID,
            strData,
          }).then((res) => {
            Modal.notice(res, 'success');
            setTimeout(() => {
              // 重新load数据
              loadAccountEvent();
            }, 10);
          });
        });
      };
      // 选择框移除
      const removeBySelect = () => {
        // 选择的数据
        const res = getSelectEvent();
        if (res.length > 0) {
          Modal.confirm('您确定要移除该项吗？', () => {
            const roleId = res[0].ACCOUNTROLE_ROLE_ID;
            let strData = [];
            // 整理删除的payload
            res.find((item) => {
              const array = strData.filter((rec) => {
                return item.ACCOUNTROLE_DEPT_ID == rec.departmentId;
              });
              if (array.length > 0) {
                strData.forEach((str) => {
                  if (str.departmentId == array[0].departmentId) {
                    str.accountIds += ',' + item.JE_RBAC_ACCOUNT_ID;
                  }
                });
              } else {
                strData.push({
                  departmentId: item.ACCOUNTROLE_DEPT_ID,
                  accountIds: item.JE_RBAC_ACCOUNT_ID,
                });
              }
            });
            // 转化payload
            strData = JSON.stringify(strData);
            // 移除接口移除数据
            removeAccountApi({ roleId, strData }).then((res) => {
              Modal.notice(res, 'success');
              setTimeout(() => {
                // reload数据
                loadAccountEvent();
              }, 10);
            });
          });
        } else {
          Modal.alert('请选择要移除的账号！', 'warning');
        }
      };

      // 获得勾选项
      const getSelectEvent = () => {
        const $table = xTable.value;
        const selectRecords = $table.getCheckboxRecords();
        return selectRecords;
      };

      // 添加人员账号
      const peopleName = ref(null);
      const peopleId = ref(null);
      const columnID = ref([]);
      const columnCode = ref([]);
      const add = () => {
        SelectWindow.show({
          title: '添加人员账号',
          type: 'grid',
          labelField: false,
          subLabelField: false,
          // 过滤JE_RBAC_DEPARTMENT_ID和USER_CODE数组数据
          querys: [
            {
              code: 'JE_RBAC_DEPARTMENT_ID',
              value: columnID.value,
              type: 'notIn',
              cn: 'or',
            },
            {
              code: 'USER_CODE',
              value: columnCode.value,
              type: 'notIn',
              cn: 'or',
            },
          ],
          orders: [{ code: 'SY_CREATETIME', type: 'DESC' }],
          configInfo: 'JE_RBAC_VDEPTUSER,,,M',
          callback: function ({ rows }) {
            if (rows.length > 0 && theCurrID.value) {
              let arr = [];
              // 得到添加数据
              rows.forEach((item) => {
                let obj = {};
                obj['departmentId'] = item.JE_RBAC_DEPARTMENT_ID;
                obj['userIds'] = item.JE_RBAC_USER_ID;
                arr.push(obj);
              });
              const addStrData = JSON.stringify(arr);
              loading.value = true;
              // 调用按部门导入接口
              importByDepartmentUsersApi({ roleId: theCurrID.value, addStrData })
                .then((res) => {
                  Modal.notice(res, 'success');
                  loading.value = false;
                  // reload数据
                  loadAccountEvent();
                })
                .catch((err) => {
                  loading.value = false;
                  Modal.alert(err.message, 'error');
                });
            }
          },
        });
      };

      // 添加开发成员
      const addDeveloper = () => {
        SelectWindow.show({
          title: '添加开发成员',
          type: 'tree',
          // 过滤JE_RBAC_DEPARTMENT_ID和USER_CODE数组数据
          querys: [
            {
              code: 'JE_RBAC_DEPARTMENT_ID',
              value: columnID.value,
              type: 'notIn',
              cn: 'or',
            },
            {
              code: 'USER_CODE',
              value: columnCode.value,
              type: 'notIn',
              cn: 'or',
            },
          ],
          orders: [{ code: 'SY_CREATETIME', type: 'DESC' }],
          configInfo: 'JE_RBAC_DEVELOPUSER,,,M',
          callback: function ({ rows }) {
            if (rows.length > 0 && theCurrID.value) {
              let arr = [];
              // 获取payload数据
              rows.forEach((item) => {
                let obj = {};
                obj['departmentId'] = item.bean.ACCOUNTDEPT_DEPT_ID;
                obj['accountId'] = item.bean.JE_RBAC_ACCOUNT_ID;
                obj['syOrgId'] = item.bean.SY_ORG_ID;
                arr.push(obj);
              });
              const addStrData = JSON.stringify(arr);
              loading.value = true;
              // 调用导入部门账号接口
              importAccountDeptByDepartmentAccounteApi({ roleId: theCurrID.value, addStrData })
                .then((res) => {
                  Modal.notice(res, 'success');
                  loading.value = false;
                  // reload数据
                  loadAccountEvent();
                })
                .catch((err) => {
                  loading.value = false;
                  Modal.alert(err.message, 'error');
                });
            }
          },
        });
      };

      // 机构筛选
      let word = '';
      const orgTitle = ref('全部机构');
      const organText = ref('all');
      // 选择机构
      const selectDepartment = (value, option) => {
        organText.value = value;
        orgTitle.value = option.label;
        if (orgTitle.value === '全部机构') {
          loadAccountEvent();
        } else {
          loadAccountEvent(organText.value);
        }
      };
      // 开发者过滤供应商
      let meta = null;
      const clickSelectEvent = () => {
        if (remark.value == 'Developer') {
          allORGs.value = allORGs.value.filter((item) => {
            return item.label != '供应商';
          });
        } else {
          allORGs.value = meta;
        }
      };
      // 机构筛选方法
      const filterNameMethod = ({ value, row }) => {
        value = word;
        return XEUtils.toValueString(row.SY_ORG_NAME).toLowerCase().indexOf(value) > -1;
      };

      // 通过机构导入账号
      const selectByOrg = (row) => {
        const value = row.id;
        SelectWindow.show({
          title: '添加机构人员账号',
          type: 'grid',
          querys: [{ code: 'SY_ORG_ID', value: value, type: '=', cn: 'and' }],
          orders: [{ code: 'SY_CREATETIME', type: 'DESC' }],
          configInfo: 'JE_RBAC_ACCOUNT,,,M',
          callback: function ({ rows }) {
            if (rows.length > 0 && theCurrID.value) {
              let arr = [];
              rows.forEach((item) => {
                arr.push(item.JE_RBAC_ACCOUNT_ID);
              });
              const ids = arr.join(',');
              // 调用通过机构导入账号接口
              importAccountByOrgsApi({ roleId: theCurrID.value, orgId: value, ids }).then((res) => {
                Modal.notice(res, 'success');
                // reload数据
                loadAccountEvent();
              });
            }
          },
        });
      };

      // 按钮置灰
      const btnFlag = ref(true);
      // 点击左侧tree的每一项的回调
      const showAccountEvent = ({ _type, _id, _nodeType }) => {
        if (_type === 'develop') {
          _currrntType = 'role';
        } else {
          _currrntType = _type;
        }
        theCurrID.value = _id;
        columnID.value = [];
        columnCode.value = [];
        if (_nodeType) {
          btnFlag.value = false;
        } else {
          btnFlag.value = true;
        }
        loadAccountEvent();
      };

      // 点击通过机构添加账号按钮
      const orgList = ref([]);
      const importORGBtn = () => {
        if (orgList.value.length > 0) return false;
        loadOrgApi({ excludeDepartment: '1' }).then((res) => {
          orgList.value = res.children;
        });
      };
      // 点击全部机构按钮
      const allORGs = ref([]);
      const clickAllOrgEvent = () => {
        loadOrgApi().then((res) => {
          const result = res.children;
          // allORGs.value = res.children;
          allORGs.value.push({
            label: '全部机构',
            value: 'all',
          });
          result.forEach((item) => {
            const obj = {};
            // 去除供应商
            obj['value'] = item.bean.JE_RBAC_ORG_ID;
            obj['label'] = item.bean.ORG_NAME;
            allORGs.value.push(obj);
          });
          meta = JSON.parse(JSON.stringify(allORGs.value));
        });
      };

      // 清除数据
      const cleanDataEvent = () => {
        // 重置数据
        _currrntType = null;
        theCurrID.value = null;
        columnID.value = [];
        columnCode.value = [];
        btnFlag.value = true;
        tableData.value = [];
      };

      VueEvent.on('leftComponent', leftComponentCB);
      VueEvent.on('showAccount', showAccountEvent);
      VueEvent.on('cleanData', cleanDataEvent);
      onUnmounted(() => {
        VueEvent.off('leftComponent', leftComponentCB);
        VueEvent.off('showAccount', showAccountEvent);
        VueEvent.off('cleanData', cleanDataEvent);
      });

      const getPopupContainer = () => {
        return document.body;
      };

      return {
        loadAccountEvent,
        tablePage,
        xTable,
        tableData,
        searchValue,
        searchEvent,
        showImport,
        remark,
        gobalBuyer,
        remove,
        removeBySelect,
        add,
        peopleName,
        peopleId,
        selectDepartment,
        filterNameMethod,
        loading,
        importORGBtn,
        clickSelectEvent,
        clickAllOrgEvent,
        allORGs,
        orgList,
        theCurrID,
        btnFlag,
        isShow,
        accountId,
        dataType,
        selectByOrg,
        orgTitle,
        getPopupContainer,
        organText,
        addDeveloper,
      };
    },
  });
</script>

<style lang="less" scoped>
  .account {
    // :deep(.je-panel-wrapper) {
    //   height: 100% !important;
    //   width: 100% !important;
    // }
    // :deep(.je-panel-item-region-default) {
    //   top: 40px !important;
    //   height: 100% !important;
    //   width: 100% !important;
    // }
    :deep(.je-panel-item-region-top) {
      border-top: 1px solid #e6e6e6;
      border-bottom: 1px solid #e6e6e6;
    }
    :deep(.keyword-lighten) {
      color: #ff0000;
    }
    :deep(.headerHeight) {
      height: 40px;
      border-radius: 0;
    }
    :deep(.vxe-table--border-line) {
      border-left: none;
      border-top: none;
    }
    .tip {
      color: #a9aba9;
      i {
        margin-left: 16px;
        margin-right: 6px;
      }
    }
    .content {
      height: 38px;
      .content-toolbar {
        overflow-x: auto;
      }
    }
    .searchWrap {
      margin: 0 0 0 auto;
      .ant-input-search {
        border-bottom-right-radius: 0;
        border-top-right-radius: 0;
      }
      .ant-input-affix-wrapper-focused {
        box-shadow: none !important;
      }
      .ant-btn {
        width: 60px;
        background: #3265f5;
      }
    }
  }
</style>
